﻿namespace MicroCloud.Utils
{
    /// <summary>
    /// 命令执行器
    /// </summary>
    [SupportedOSPlatform("windows"), SupportedOSPlatform("linux"), SupportedOSPlatform("macos")]
    public class CommandExecutor
    {
        /// <summary>
        /// 执行命令并获取输出结果
        /// </summary>
        /// <param name="command">命令字符串</param>
        /// <returns>输出结果</returns>
        public static string ExecuteCommand(string command)
        {
            string output = "";
            if (RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD))
            {
                throw new NotSupportedException(I18N.T("不支持的平台 {0}", "FreeBSD"));
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                output = LinuxCommandExecutor.ExecuteCommand(command);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                output = MacOSCommandExecutor.ExecuteCommand(command);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                output = WindowsCommandExecutor.ExecuteCommand(command);
            }
            return output;
        }

        /// <summary>
        /// 执行命令文件并获取输出结果
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <returns>输出结果</returns>
        public static string ExecuteCommandFile(string fileName)
        {
            Check.FileExists(fileName, nameof(fileName));

            string output = "";
            if (RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD))
            {
                throw new NotSupportedException(I18N.T("不支持的平台 {0}", "FreeBSD"));
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                output = LinuxCommandExecutor.ExecuteCommandFile(fileName);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                output = MacOSCommandExecutor.ExecuteCommandFile(fileName);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                output = WindowsCommandExecutor.ExecuteCommandFile(fileName);
            }
            return output;
        }

    }
}
